package com.itheima.mybatis.test.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ：sean
 * @date ：Created in 2020/7/5
 * @description ：
 * @version: 1.0
 */
@Configuration
@ComponentScan("com.itheima.mybatis.test")
@MapperScan("com.itheima.mybatis.test.dao")
public class MybatisConfig {
	@Bean
	public DataSource dataSource(){
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUsername("root");
		dataSource.setPassword("root");
		dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/itheima_mm?characterEncoding=utf-8");
		return dataSource;
	}
	@Bean
	public SqlSessionFactory sqlSessionFactory() throws Exception {
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		// 配置数据源
		factoryBean.setDataSource(dataSource());  // 配置mapper资源路径
		factoryBean.setMapperLocations(resolveMapperLocations()); // 获取sqlSessionFactory对象
    SqlSessionFactory sqlSessionFactory = factoryBean.getObject();
		System.out.println("sqlSessionFactory");
		return sqlSessionFactory;
	}
  private Resource[] resolveMapperLocations() {
    ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
    List<String> mapperLocations = new ArrayList<>();
    mapperLocations.add("classpath*:mapper/*.xml");
    List<Resource> resources = new ArrayList();
    if (mapperLocations != null) {
      for (String mapperLocation : mapperLocations) {
        try {
          Resource[] mappers = resourceResolver.getResources(mapperLocation);
          resources.addAll(Arrays.asList(mappers));
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return resources.toArray(new Resource[resources.size()]);
  }
}
